package com.andy.qhb.controller.game;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.andy.qhb.base.RespVO;
import com.andy.qhb.controller.GameController;
import com.andy.qhb.dao.DaoUtils;
import com.andy.qhb.dao.vo.Where;
import com.andy.qhb.entity.UsrFriends;
import com.andy.qhb.entity.UsrMsgLog;
import com.andy.qhb.entity.UsrUser;
import com.andy.qhb.game.GameUser;
import com.andy.qhb.game.GlobalHttp;
import com.andy.qhb.utils.GoConstant;
import com.andy.qhb.utils.JsonUtils;

@Controller
@RequestMapping(value="game/api")
public class Api111Controller extends GameController{
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	/**
	 * 添加好友
	 * @param session
	 * @param data
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="111")
	public RespVO action(HttpSession session,String data) throws Exception{
		GameUser user = getUser(session);
		Map<String, Object> reqData = JsonUtils.json2Map(data);
		Long uid = MapUtils.getLong(reqData, "uid");
		if(user.getId().equals(uid)) return RespVO.createErrorJsonResonse("不能添加自己");
		UsrUser usrUser = DaoUtils.getOneSql(UsrUser.class, "select id,nick_name,icon from usr_user where id=?", uid);
		if(usrUser == null){
			return RespVO.createErrorJsonResonse("用户不存在");
		}else{
			UsrFriends otherFriend = DaoUtils.getOne(UsrFriends.class, Where.eq("uid", uid));
			if(otherFriend.getFids().indexOf(user.getId()+",") > 0 ) {
				return RespVO.createErrorJsonResonse("已经添加为好友");
			}
			List<UsrMsgLog> list = DaoUtils.getList(UsrMsgLog.class, Where.eq("uid_other", uid),
					Where.eq("type", GoConstant.MSG_0));
			if(list != null) {
				for(UsrMsgLog log:list) {
					if(log.getUid().equals(user.getId())) {
						// 已经申请
						return RespVO.createSuccessJsonResonse(uid);
					}
				}
			}
			
			UsrMsgLog msgLog = new UsrMsgLog();
			msgLog.setType(GoConstant.MSG_0);
			msgLog.setUid(user.getId());
			msgLog.setUidOther(usrUser.getId());
			msgLog.setJson(JsonUtils.object2JsonString(user.forOther()));
			
			GameUser user2 = GlobalHttp.getUser(uid);
			if(user2 != null){
				user2.addRlog(msgLog);
			}
			
			DaoUtils.insert(msgLog);
			
			return RespVO.createSuccessJsonResonse(uid);
		}
		
		
	}
	
	
}